package top.lshaci.learning.thread;

/**
 * JoinNotReleaseLockTest
 *
 * @author lshaci
 * @since 1.0.0
 */
public class JoinNotReleaseLockTest {

    /**
     * jps
     * jstack $PID
     *
     * "main" #1 prio=5 os_prio=0 tid=0x0000000002872800 nid=0x350 in Object.wait() [0x000000000273f000]
     *    java.lang.Thread.State: WAITING (on object monitor)
     *         at java.lang.Object.wait(Native Method)
     *         - waiting on <0x000000078096f158> (a java.lang.Thread)
     *         at java.lang.Thread.join(Thread.java:1252)
     *         - locked <0x000000078096f158> (a java.lang.Thread)
     *         at java.lang.Thread.join(Thread.java:1326)
     *         at top.lshaci.learning.thread.JoinNotReleaseLockTest.main(JoinNotReleaseLockTest.java:34)
     *         - locked <0x000000078096f148> (a java.lang.Object)
     *
     * "t1 -- " #11 prio=5 os_prio=0 tid=0x000000001b993000 nid=0x16b8 waiting for monitor entry [0x000000001c26e000]
     *    java.lang.Thread.State: BLOCKED (on object monitor)
     *         at top.lshaci.learning.thread.JoinNotReleaseLockTest.lambda$main$0(JoinNotReleaseLockTest.java:23)
     *         - waiting to lock <0x000000078096f148> (a java.lang.Object)
     *         at top.lshaci.learning.thread.JoinNotReleaseLockTest$$Lambda$1/381259350.run(Unknown Source)
     *         at java.lang.Thread.run(Thread.java:748)
     *
     * 1、main线程锁住了：locked 0x000000078096f148
     * 2、t1  线程在等待锁：waiting to lock 0x000000078096f148
     */
    public static void main(String[] args) throws Exception {
        final Object lock = new Object();

        Thread t1 = new Thread(() -> {
            synchronized (lock) {
                for (int i = 0; i < 100; i++) {
                    System.out.println("t1 -- " + i);
                }
            }
        }, "t1 -- ");
        t1.start();

        synchronized (lock) {
            for (int i = 0; i < 100; i++) {
                if (i == 20) {
                    try {
                        t1.join();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(Thread.currentThread().getName() + " -- " + i);
            }
        }
    }
}
